#!/bin/sh
# my_ssh_pubkey
# my_email
# sshr_port
# sshr_port_len
# sshr_port_base

SCRIPT_DIR=$(dirname $(realpath $0))
PROJECT_DIR=$(dirname $SCRIPT_DIR)

. $PROJECT_DIR/lib/http.sh
. $PROJECT_DIR/lib/env.sh
. $PROJECT_DIR/lib/email.sh

sshr_ip=$LKP_SERVER
[ -n "$sshr_port" ]      || sshr_port=5050
[ -n "$sshr_port_len" ]  || sshr_port_len=2000
[ -n "$sshr_port_base" ] || sshr_port_base=50000

generate_key_file()
{
	echo -e "y\n" | ssh-keygen -t rsa -b 2048 -N '' -f /etc/ssh/ssh_host_rsa_key
}

run_ssh()
{
	[ -n "$my_ssh_pubkey" ] || return
	umask 0077
	mkdir -p /root/.ssh
	echo "$my_ssh_pubkey" > /root/.ssh/authorized_keys
	if is_docker; then
		generate_key_file
		sshd_path=$(cmd_path sshd)
		$sshd_path -q
	else
		systemctl start sshd
	fi
}

set_port()
{
	[ -n "$my_ssh_pubkey" ] || return

	for i in $(seq 1 10)
	do
		port=$(($(date +%s%N)%$sshr_port_len+$sshr_port_base))
		ssh -o StrictHostKeyChecking=no -o ExitOnForwardFailure=yes -o TCPKeepAlive=yes \
		    -Nf -R $port:localhost:22 sshr@"$sshr_ip" -p "$sshr_port" &>/dev/null
		[ $? -eq 0 ] && return
	done
	port=""
}

run_email()
{
	[ -n "$my_email" ] || return 0

	deadline=$(date -d "$runtime seconds" +"%Y-%m-%d %H:%M:%S")
	if [ -n "$port" ]; then
		send_email "borrow_success"
	else
		send_email "borrow_failed"
	fi
}

run_ssh
set_port
report_ssh_port $port
run_email
